<template>
	<div>
		<el-form ref="form" :model="form" :rules="rules">
			<el-form-item prop="appid" label="选择科目" v-if="isTrain">
				<el-select placeholder="请选择科目" v-model="form.appid">
					<el-option v-for="miniApp in miniApps" :key="miniApp.id" :label="miniApp.name"
						:value="miniApp.id"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item prop="type" label="题目类型">
				<div style="width: 50vw;display: inline-block;">
					<el-radio-group v-model="form.type" @change="changetype">
						<el-radio v-for="(type, index) in typesData" :key="index" :label="type.id" :value="type.id"
							class="width130 margin-top10 height25">{{ type.name }}
						</el-radio>
					</el-radio-group>
				</div>
				<div class="blue-text font-size14 margin-left20 width200" style="display: inline-block;" @click="clickShow"
					v-if="!isSmall">
					{{clickShow?'展开':'隐藏'}}
				</div>
			</el-form-item>
			<el-form-item label="题目分类" :rules="[{ required: true, message: '请选择', trigger: 'blur' }]">
				<div v-if="isSmall">
					<el-select v-model="form.classId" placeholder="请选择" clearable class="margin-right30">
						<el-option v-for="item in classIdData" :key="item.id" :label="item.name" :value="item.id"> </el-option>
					</el-select>
				</div>
				<div class="row-me flex-wrap category" v-else>
					<el-form-item prop="categoryId3" label="章节分类" :rules="[{ required: true, message: '请选择', trigger: 'blur' }]"
						label-width="80">
						<el-select v-model="form.categoryId3" placeholder="章节分类" clearable @change="onCategoryChange3"
							class="margin-right30">
							<el-option v-for=" item in categoryId3s" :key="item.id" :label="item.name" :value="item.id"
								:style="{'color': item.color?item.color:''}"> </el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="categoryId2" label="模块分类" :rules="[{ required: true, message: '请选择', trigger: 'blur' }]">
						<el-select v-model="form.categoryId2" placeholder="模块分类" clearable @change="onCategoryChange2"
							class="margin-right30">
							<el-option v-for="item in categoryId2s" :key="item.id" :label="item.name" :value="item.id"> </el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="categoryId1" label="综合分类" :rules="[{ required: true, message: '请选择', trigger: 'blur' }]">
						<el-select filterable v-model="form.categoryId1" placeholder="综合分类" clearable @change="onCategoryChange1">
							<el-option v-for="item in categoryId1s" :key="item.id" :label="item.name" :value="item.id"> </el-option>
						</el-select>
					</el-form-item>
				</div>
			</el-form-item>
			<div class="row-me row-center flex-wrap category">
				<el-form-item label="题目属性" prop="properType" v-if="!isTheme" label-width="80">
					<el-radio-group v-model="form.properType">
						<el-radio :label="1">普通题</el-radio>
						<el-radio :label="2">作废题</el-radio>
						<el-radio :label="3">争议题</el-radio>
						<el-radio :label="4">重复题</el-radio>
					</el-radio-group>
					<el-button v-if="isEntry" @click="clickEntry" type="primary" class="margin-left20">快速录入
					</el-button>
				</el-form-item>
				<el-form-item label="功能区" class="gongnnegqv margin-left50" label-width="80">
					<el-checkbox-group v-model="domainArr">
						<el-checkbox label="启用富文本"></el-checkbox>
						<el-checkbox label="数学题" @change="mathChange"></el-checkbox>
						<el-checkbox label="英语题" @change="englishChange"></el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item>
					<el-date-picker v-model="date" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日"
						value-format="yyyy-MM-dd" class="margin-left70">
					</el-date-picker>
				</el-form-item>
			</div>
			<el-form-item label="题目标签">
				<div class="row-me">
					<el-select v-model="form.labelIds" multiple filterable placeholder="请选择题目标签" class="flex1"
						@change="$forceUpdate()">
						<el-option v-for="item in labelTypeList" :key="item.id" :label="item.name" :value="item.id">
							<div class="row-me">
								<span class="flex1">{{item.name+'['+item.questionCount+']'}}</span>
								<span>{{item.tails.typename}}</span>
							</div>
						</el-option>
					</el-select>
					<div class="row-me row-center flex-wrap margin-left30 flex1">
						<span class="color9D9FA3 margin-right10">历史标签</span>
						<el-tag class="margin-right20 pointer" v-for="item in labelTypeList2" :key="item.id"
							@click="clickTag(item)">{{item.name}}</el-tag>
					</div>
				</div>
			</el-form-item>
			<el-form-item v-if="!domainArr.includes('启用富文本')" prop="title" label="题目" label-width="80">
				<el-input @input="shibieluru()" @change="shibieluru" type="textarea" v-model="form.title" placeholder="请输入题干"
					rows="6" class="width60vw"></el-input>
			</el-form-item>
			<el-form-item v-if="domainArr.includes('启用富文本')" prop="title" label="题目">
				<div class="row-me posRelative">
					<vue-ueditor-wrap v-model="form.title" editor-id="editor1" :config="editorConfig"
						:editorDependencies="['ueditor.config.js','ueditor.all.js']" style="width: 60%;" />
				</div>
			</el-form-item>

			<div v-if="form.type==100" class="width60vw margin-left80 font-size14 color252525 margin-bottom60">
				<el-button type="primary" @click="handleEdit">添加试题选项</el-button>
				<el-button type="primary" @click="batchAddVisible=true">批量添加</el-button>
				<div class="row-me flex-wrap margin-top20" v-for="(item,index) in clozeList" :key="index">
					<div class="width100">第{{$.numberToChinese(index+1)}}题</div>
					<div class="flex1 margin-right50">
						<div class="row-me space-between">
							<span v-for="(val,i) in item.content" :key="i"
								class="margin-right10">{{optionsArr[i]}}.{{val.content}}</span>
						</div>
						<div class="margin-top10 row-me flex-wrap">
							答案：<span v-html="item.answer"></span>
						</div>
						<div class="margin-top10">解析：<span v-html="item.textExplain"></span></div>
					</div>
					<div class="row-me">
						<el-button type="text" @click="handleEdit(item,index+1)">编辑</el-button>
						<el-button type="text" @click="clozeList.splice(index,1)">删除</el-button>
					</div>
				</div>
			</div>
			<el-form-item v-if="childExamList.length!=0" class="margin-left80">
				<div class="row-me row-center" v-for="(item,index) in childExamList" :key="item.id">
					<div class="examText row-me">
						<span class="margin-right5">{{index+1}}、({{item.type.name}})</span><span class="flex1"
							v-html="item.title"></span>
					</div>
					<div class="margin-left10 pointer font-size16">
						<i class="el-icon-sort margin-right10" @click="clickSort(index)"></i>
						<i class="el-icon-error" @click="clickDel(item.id)"></i>
					</div>
				</div>
			</el-form-item>
			<el-form-item v-if="form.type==99||form.type==114||form.type==115||form.type==113" class="margin-left80">
				<el-button type="primary" @click="addChildExam">添加子题目</el-button>
			</el-form-item>
			<template v-else-if="form.type!=100">
				<el-form-item label="选项" v-if="keguan && panduan === false">
					<el-radio-group v-model="form.optionType" @change="onChange" v-if="!domainArr.includes('数学题')">
						<el-radio :label="1">文字选项</el-radio>
						<el-radio :label="2">图片选项</el-radio>
					</el-radio-group>
					<div>
						<el-input type="textarea" class="width60vw margin-left80" v-model="form.optionsStr"
							placeholder="请输入选项，每个选项换行填写" rows="6" v-if="form.optionType==1" @input="$forceUpdate()">
						</el-input>
					</div>
					<div v-if="form.optionType==2" class="margin-left80 margin-top40">
						<div v-for="(item,index) in imgOptionData" :key="index" class="row-me margin-top20">
							<div class="blue-text width60" v-if="imgOptionData.length==index+1"><i
									class="el-icon-circle-plus-outline margin-right10" @click="clickPush" v-if="index!=5"></i><i
									class="el-icon-remove-outline margin-right10" @click="clickSubtract(index)" v-if="index!=0"></i>
							</div>
							<div v-else class="width60"></div>
							<div class="color606266 width60">选项{{optionsArr[index]}}</div>
							<div v-if="domainArr.includes('数学题')" class="row-me width60vw">
								<el-image v-if="judgeImg(item.content)" :src="item.content" fit="scale-down" class="width100"
									:preview-src-list="[item.content]"></el-image>
								<el-input v-model="item.content" class="flex1 margin-right20" placeholder="请输入选项" v-else></el-input>
								<div class="row-me row-center pointer margin-left20" @click="item.isShow=true">
									<div class="row-me row-center pointer" @click="clickFormula(item,index)">
										<img src="@/assets/images/formula.png" alt="" class="img24 margin-right10">
										<span class="color1890FF width80">输入公式</span>
									</div>
									<el-button type="text" @click="clickImgOpen(index)">图片库</el-button>
								</div>
							</div>
							<el-upload :action="uploadUrl" class="row-me" list-type="picture-card" :file-list="item.fileList"
								:on-success="(res,file)=>handleUploadSuccess(res,file,index)" :limit="1" v-else>
								<i class="el-icon-plus"></i>
							</el-upload>
						</div>
					</div>
				</el-form-item>
				<div v-if="keguan">
					<el-form-item label="参考答案" prop="answer" v-if="danxuan">
						<el-radio-group v-model="form.answer">
							<el-radio label="A"></el-radio>
							<el-radio label="B"></el-radio>
							<el-radio label="C"></el-radio>
							<el-radio label="D"></el-radio>
							<el-radio label="E"></el-radio>
							<el-radio label="F"></el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="参考答案" prop="answerN" v-if="duoxuan">
						<el-checkbox-group v-model="form.answerN">
							<el-checkbox label="A"></el-checkbox>
							<el-checkbox label="B"></el-checkbox>
							<el-checkbox label="C"></el-checkbox>
							<el-checkbox label="D"></el-checkbox>
							<el-checkbox label="E"></el-checkbox>
							<el-checkbox label="F"></el-checkbox>
						</el-checkbox-group>
					</el-form-item>
					<el-form-item label="参考答案" prop="answer" v-if="panduan">
						<el-radio-group v-model="form.answer">
							<el-radio label="正确">正确</el-radio>
							<el-radio label="错误">错误</el-radio>
						</el-radio-group>
					</el-form-item>
					<el-form-item label="解析" prop="textExplain">
						<el-checkbox v-model="isAnalysis">启用富文本</el-checkbox>
						<div class="row-me margin-left80" v-if="isAnalysis">
							<vue-ueditor-wrap v-model="form.textExplain" editor-id="editor2" :config="editorConfig2"
								:editorDependencies="['ueditor.config.js','ueditor.all.js']" style="width: 60%;" />
						</div>
						<div v-else>
							<el-input type="textarea" v-model="form.textExplain" placeholder="请输入解析" rows="6"
								class="width60vw row-me margin-left80" @change="$forceUpdate()" @input="$forceUpdate()">
							</el-input>
						</div>
					</el-form-item>
				</div>
				<div v-if="zhuguan&&questionId">
					<el-form-item prop="answer" label="参考答案">
						<div class="row-me">
							<vue-ueditor-wrap ref="editor" v-model="form.answer" editor-id="editor5" :config="editorConfig5"
								:editorDependencies="['ueditor.config.js','ueditor.all.js']" style="width: 60%;" />
						</div>
					</el-form-item>
				</div>
				<div v-else-if="zhuguan">
					<el-form-item prop="answer" label="参考答案">
						<div class="row-me">
							<vue-ueditor-wrap ref="editor" v-model="form.answer" editor-id="editor3" :config="editorConfig3"
								:editorDependencies="['ueditor.config.js','ueditor.all.js']" style="width: 60%;" />
						</div>
					</el-form-item>
				</div>
			</template>
			<el-form-item class="margin-left80">
				<el-button type="primary" @click="submitQuestionCheck" v-if="$.isEmpty(examId)">检测重复度</el-button>
				<el-button type="primary" @click="submitQuestion()">立即提交</el-button>
				<el-button type="mary" @click="resetting()">重置</el-button>
				<el-button type="mary" @click.stop="returnIndex()">取消</el-button>
			</el-form-item>
		</el-form>

		<repeatedQuestions ref="repeatedQuestions" :form="form" :isSmall="isSmall">
		</repeatedQuestions>

		<el-dialog title="公式" :visible.sync="formulaVisible" width="60%" :modal-append-to-body="false" append-to-body>
			<latexEasy @handleOk="handleOk"></latexEasy>
		</el-dialog>

		<!-- 新增编辑完形填空试题选项 -->
		<el-dialog :title="title" :visible.sync="editVisible" width="650px" :modal-append-to-body="false" append-to-body>
			<el-form :model="clozeForm" label-width="60px">
				<el-form-item :label="optionsArr[index]+'.'" v-for="(item,index) in clozeForm.content" :key="index" required>
					<el-input placeholder="请输入" v-model="item.content" class="width300"></el-input>
				</el-form-item>
				<el-form-item label="答案:" required>
					<el-radio-group v-model="clozeForm.answer">
						<el-radio :label="optionsArr[index]" v-for="(item,index) in 4" :key="index">{{optionsArr[index]}}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="解析:">
					<el-checkbox v-model="isCloze">启用富文本</el-checkbox>
					<div v-if="isCloze" class="width100Per">
						<div class="row-me margin-left80">
							<vue-ueditor-wrap v-model="clozeForm.textExplain" editor-id="editor4" :config="editorConfig4"
								:editorDependencies="['ueditor.config.js','ueditor.all.js']" style="width: 60%;" />
						</div>
					</div>
					<el-input v-else type="textarea" v-model="clozeForm.textExplain" placeholder="请输入解析" rows="6"
						class="row-me margin-left80 width500">
					</el-input>
				</el-form-item>
			</el-form>
			<span slot="footer">
				<el-button @click="editVisible=false">取 消</el-button>
				<el-button type="primary" @click="handleSave">确 认</el-button>
			</span>
		</el-dialog>

		<!-- 批量添加试题选项 -->
		<el-dialog title="批量添加试题选项" :visible.sync="batchAddVisible" width="60%" :modal-append-to-body="false"
			append-to-body>
			<div>
				<el-input type="textarea" rows="18" class="width80Per" v-model="batchContent"></el-input>
			</div>
			<el-button type="primary" class="margin-top10" @click="clickIdentify">点击识别</el-button>
			<div class="row-me flex-wrap margin-top20 font-size16 color252525" v-for="(item,index) in resultArr" :key="index">
				<div class="width100">第{{$.numberToChinese(index+1)}}题</div>
				<div class="flex1 margin-right50">
					<div class="row-me space-between">
						<span v-for="(val,i) in item.content" :key="i" class="margin-right10">{{val.title}}.{{val.content}}</span>
					</div>
					<div class="margin-top10">
						答案：<span v-html="item.answer"></span>
					</div>
					<div class="margin-top10">解析：<span v-html="item.textExplain"></span></div>
				</div>
				<div class="row-me">
					<el-button type="text" @click="handleEdit(item,index+1)">编辑</el-button>
					<el-button type="text" @click="resultArr.splice(index,1)">删除</el-button>
				</div>
			</div>
			<span slot="footer">
				<el-button @click="batchAddVisible=false">取 消</el-button>
				<el-button type="primary" @click="batchAddSave">确定添加</el-button>
			</span>
		</el-dialog>

		<tabPane ref="tabPane" title="选择子试题" :sideData="smallTypeList" @handleOk="childHandleOk"></tabPane>

		<imgLibrary ref="imgLibrary" @handleImgOk="handleImgOk"></imgLibrary>
	</div>
</template>

<script>
	import latexEasy from '@/components/latexEasy'
	import tabPane from '@/components/tabPane'
	import repeatedQuestions from '@/components/repeatedQuestions'
	import imgLibrary from "@/components/imgLibrary"
	export default {
		name: 'examQuestions',
		props: {
			isEntry: {
				type: Boolean,
				default: false
			},
			isTheme: {
				type: Boolean,
				default: false
			},
			editForm: {
				type: Object,
			},
			isChild: {
				type: Boolean,
				default: false
			},
			questionId: {
				default: null
			},
			isSmall: {
				type: Boolean,
				default: false
			}
		},
		components: {
			tabPane,
			repeatedQuestions,
			latexEasy,
			imgLibrary
		},
		watch: {
			questionId(newval, oldval) {
				console.log("pppp")
				this.examId = newval
				this.getType()
				this.getDetail()
			}
		},
		data() {
			let that = this
			return {
				rules: {
					type: {
						required: true,
						message: '请选择题目类型',
						trigger: 'change'
					},
					properType: {
						required: true,
						message: '请选择题目属性',
						trigger: 'change'
					},
					title: {
						required: true,
						message: '请选择输入题目',
						trigger: 'blur'
					},
					answer: {
						required: true,
						message: '请选择答案',
						trigger: 'blur'
					},
					answerN: {
						required: true,
						message: '请选择答案',
						trigger: 'change'
					},
					appid: {
						required: true,
						message: '请选择科目',
						trigger: 'change'
					}
				},
				typesData: [], //类型集合
				form: {
					optionType: 1,
					answer: '',
					answerN: [],
					labelIds: [],
					properType: 1
				},
				categoryId1s: [],
				categoryId2s: [],
				categoryId3s: [],
				classIdData: [],
				isShow: false, //展开收起
				typeList: [],
				domainArr: [], //功能区
				isRepeat: false,
				isEnter: false,
				isAutoIdentify: false,
				autoIdentifyStr: '', //自动识别试题
				childExamList: [],
				keguan: true,
				panduan: false,
				danxuan: true,
				duoxuan: false,
				zhuguan: false,
				daan: false,
				imgOptionData: [{
						content: ''
					},
					{
						content: ''
					},
					{
						content: ''
					}, {
						content: ''
					}
				],
				optionsArr: ['A', 'B', 'C', 'D', 'E', 'F'],
				uploadUrl: this.$host + '/file/upload?token=' + localStorage.getItem('token'),
				isAnalysis: false,
				date: '',
				labelTypeList: [],
				labelTypeList2: [],
				option: {},
				repeatData: [],
				examId: '',
				formulaVisible: false,
				isMath: false,
				imgIndex: 0,
				editVisible: false,
				isCloze: false,
				clozeList: [],
				clozeForm: {
					content: [{
						content: ''
					}, {
						content: ''
					}, {
						content: ''
					}, {
						content: ''
					}]
				},
				clozeIndex: null,
				title: '',
				miniApps: [],
				isTrain: false,
				isMock: false,
				imgTab: 1,
				batchAddVisible: false,
				batchContent: '',
				editorConfig: {
					serverUrl: process.env.BASE_API + "/file/upload",
					UEDITOR_HOME_URL: '/static/UEditor/',
					toolbarCallback: function(cmd, editor) {
						switch (cmd) {
							case 'insertimage':
								that.imgTab = 1
								that.$refs.imgLibrary.show()
								return true;
						}
					}
				},
				editorConfig2: {
					serverUrl: process.env.BASE_API + "/file/upload",
					UEDITOR_HOME_URL: '/static/UEditor/',
					toolbarCallback: function(cmd, editor) {
						switch (cmd) {
							case 'insertimage':
								that.imgTab = 2
								that.$refs.imgLibrary.show()
								return true;
						}
					}
				},
				editorConfig3: {
					serverUrl: process.env.BASE_API + "/file/upload",
					UEDITOR_HOME_URL: '/static/UEditor/',
					toolbarCallback: function(cmd, editor) {
						switch (cmd) {
							case 'insertimage':
								that.imgTab = 3
								that.$refs.imgLibrary.show()
								return true;
						}
					}
				},
				editorConfig4: {
					serverUrl: process.env.BASE_API + "/file/upload",
					UEDITOR_HOME_URL: '/static/UEditor/',
					toolbarCallback: function(cmd, editor) {
						switch (cmd) {
							case 'insertimage':
								that.imgTab = 4
								that.$refs.imgLibrary.show()
								return true;
						}
					}
				},
				editorConfig5: {
					serverUrl: process.env.BASE_API + "/file/upload",
					UEDITOR_HOME_URL: '/static/UEditor/',
					toolbarCallback: function(cmd, editor) {
						switch (cmd) {
							case 'insertimage':
								that.imgTab = 3
								that.$refs.imgLibrary.show()
								return true;
						}
					}
				},
				resultArr: [],
				smallTypeList: [],
				optionIndex: 0,
				indexArr: [],
			}
		},
		mounted() {
			this.date = this.$.getNowDate()
			this.getType()
			this.getSort()
			this.getTypeList()
			this.getQuestionLabelThree()
			if (this.questionId) {
				this.examId = this.questionId
				this.getDetail()
			}
			this.indexArr = []
			for (var i = 0; i < 20; i++) {
				this.indexArr.push((i + 1) + '.')
				this.indexArr.push((i + 1) + '、')
				this.indexArr.push((i + 1) + '：')
				this.indexArr.push((i + 1) + ':')
			}
		},
		methods: {
			showDetail() {
				this.getType()
				this.examId = this.questionId
				this.getDetail()
			},
			judgeImg(content) {
				let type = ['.jpg', '.png', '.jpeg', '.svg']
				for (let item of type) {
					if (content.indexOf(item) != -1) {
						return true
					}
				}
				return false
			},
			//打开图片库
			clickImgOpen(index) {
				this.imgTab = 5
				this.$refs.imgLibrary.show()
				this.optionIndex = index
			},
			onChange() {
				for (let item of this.imgOptionData) {
					if (item.content) {
						item.fileList = [{
							url: item.content
						}]
					}
				}
			},
			//截取题干
			parseTextToQuestions(text) {
				const parts = text.split(/(?=\d+\.)/).filter((part) => part.trim() !== "");
				let questions = parts.map((part) => {
					var index = part.indexOf('A.')
					var optionIndex = part.indexOf('答案')
					var option = part.substring(index - 1, optionIndex).split('\n').filter(item => item)
					var content = []
					for (let item of option) {
						content.push({
							title: item.split('.')[0],
							content: item.split('.')[1].trim()
						})
					}
					var answerIndex = part.indexOf('解析')
					var answer = part.substring(optionIndex - 1, answerIndex).trim().slice(3)
					var textExplain = part.substring(answerIndex - 1).trim().slice(3)
					return {
						content,
						answer,
						textExplain
					}
				});
				return questions.filter((q) => q.answer);
			},
			clickIdentify() {
				this.resultArr = this.parseTextToQuestions(this.batchContent)
				console.log(this.resultArr, "this.resultArr")
			},
			//批量添加
			batchAddSave() {
				this.clozeList.push(...this.resultArr)
				this.batchAddVisible = false
			},
			//点击图片库
			clickImg(index) {
				this.imgTab = index
				this.$refs.imgLibrary.show()
			},
			handleImgOk(data) {
				switch (this.imgTab) {
					case 1:
						this.form.title = this.form.title + `<img src='${data}'>`
						break;
					case 2:
						this.form.textExplain = this.form.textExplain + `<img src='${data}'>`
						break;
					case 3:
						this.form.answer = this.form.answer + `<img src='${data}'>`
						break;
					case 4:
						this.clozeForm.textExplain = this.clozeForm.textExplain + `<img src='${data}'>`
						break;
					case 5:
						let content = data
						this.$set(this.imgOptionData[this.optionIndex], 'content', content)
						break;
				}
			},
			//点击历史标签
			clickTag(item) {
				if (this.form.labelIds) {
					this.form.labelIds.push(item.id)
				} else {
					this.form.labelIds = [item.id]
				}
			},
			childHandleOk(data) {
				this.childExamList = [...this.childExamList, ...data]
			},
			//获取历史标签
			async getQuestionLabelThree() {
				let role = localStorage.getItem('roleType')
				let roleType;
				if (role == 3) {
					roleType = 1
				}
				const res = await this.$postForm('/admin/label/questionLabelThree', {
					roleType
				})
				if (res.code == 1000) {
					this.labelThreeData = res.data
				}
			},
			show(row, type = 0) {
				this.getTypeList()
				if (type == 3) { //试题列表里的批量导入结果
					this.isMock = true
					this.form = row
					this.form.optionType = 1
					let list = this.form.optionList
					let optionsStr = ''
					for (var i = 0; i < list.length; ++i) {
						if (i == list.length - 1) {
							optionsStr += list[i].title + '.' + list[i].content;
						} else {
							optionsStr += list[i].title + '.' + list[i].content + '\n';
						}
					}
					this.form.optionsStr = optionsStr.substring(0, optionsStr.length);
					if (this.form.answer && this.form.answer.length != 0) {
						this.form.answerN = this.form.answer.split(',')
					}
					this.changetype(this.form.type)
				} else {
					this.examId = row
					this.getDetail()
				}
				if (type == 2) { //添加到题库系统
					this.isTrain = true
					this.getAll()
				}
			},
			//获取科目
			async getAll() {
				const res = await this.$get('/admin/minis/getAll')
				if (res.code == 1000) {
					this.miniApps = res.data;
				}
			},
			handleSave() {
				for (let item of this.clozeForm.content) {
					if (this.$.isEmpty(item.content)) {
						this.$message.warning('请输入选项!')
						return
					}
				}
				if (this.$.isEmpty(this.clozeForm.answer)) {
					this.$message.warning('请选择答案!')
					return
				}
				if (this.clozeIndex) {
					this.clozeList[this.clozeIndex - 1] = this.clozeForm
				} else {
					this.clozeList.push(this.clozeForm)
				}
				this.editVisible = false
			},
			//新增编辑完形填空
			handleEdit(row, index) {
				if (row.answer) {
					this.title = '编辑试题选项'
					this.clozeForm = JSON.parse(JSON.stringify(row))
					this.clozeIndex = index
				} else {
					this.clozeIndex = null
					this.title = '新增试题选项'
					this.clozeForm = {
						content: [{
							content: ''
						}, {
							content: ''
						}, {
							content: ''
						}, {
							content: ''
						}]
					}
				}
				this.editVisible = true
			},
			// 点击公式
			clickFormula(item, index) {
				this.imgIndex = index
				this.formulaVisible = true
			},
			//获取公式值
			handleOk(data) {
				if (data) {
					let a = this.svgToBase64(data.svg)
					this.$postForm('/api/upload/uploadBase64', {
						file: a
					}).then(res => {
						this.imgOptionData[this.imgIndex].content = res.data
					})
				}
				this.formulaVisible = false
			},
			svgToBase64(svg) {
				return window.btoa(unescape(encodeURIComponent(svg)))
			},
			//获取详情
			async getDetail() {
				const res = await this.$get('/admin/question/getQuestionById', {
					id: this.examId
				})
				if (res.code == 1000) {
					this.form = res.data
					this.form.type = res.data.type.value
					if (this.form.clozeList && this.form.clozeList.length != 0) {
						if (this.form.type == 100) {
							this.clozeList = this.form.clozeList
							for (let item of this.clozeList) {
								item.content = item.content ? JSON.parse(item.content) : []
							}
						}
						if (this.form.type == 99 || this.form.type == 114 || this.form.type == 115 || this.form.type == 113) {
							this.childExamList = this.form.clozeList
						}
					}
					if (this.form.function) {
						this.domainArr = this.form.function.split(',')
					} else {
						this.domainArr = []
					}
					if (res.data.labelIds) {
						let labelIds = this.form.labelIds.split(',')
						labelIds = labelIds.map(Number)
						this.$set(this.form, 'labelIds', labelIds)
					}
					if (res.data.labelName && res.data.labelName.length != 0) {
						let arr = Array.from(res.data.labelName, ({
							id
						}) => id)
						this.$set(this.form, 'labelIds', arr)
					}
					if (res.data.answer && res.data.answer.length != 0) {
						this.form.answerN = res.data.answer.split(',')
					}
					var list = this.form.optionList
					var optionsStr = '';
					if (this.form.optionType == 2 && this.form.optionList) {
						this.imgOptionData = []
						for (let item of this.form.optionList) {
							this.imgOptionData.push({
								content: item.content,
								fileList: [{
									url: item.content,
									name: item.title
								}]
							})
						}
					}
					if (this.$.isEmpty(list)) {
						this.form.optionsStr = ''
					} else {
						for (var i = 0; i < list.length; ++i) {
							if (i == list.length - 1) {
								optionsStr += list[i].title + '.' + list[i].content;
							} else {
								optionsStr += list[i].title + '.' + list[i].content + '\n';
							}
						}
						this.form.optionsStr = optionsStr.substring(0, optionsStr.length);
					}
					this.changetype(this.form.type)
				}
			},
			//获取标签下拉
			async getTypeList() {
				const res = await this.$post('/admin/label/labelList')
				if (res.code == 1000) {
					this.labelTypeList = res.data.list
					if (this.labelTypeList && this.labelTypeList.length > 3) {
						this.labelTypeList2 = this.labelTypeList.slice(this.labelTypeList.length - 3)
					} else {
						this.labelTypeList2 = this.labelTypeList.slice(this.labelTypeList.length)
					}
				}
			},
			addChildExam() {
				this.$refs.tabPane.show()
			},
			returnIndex() {
				this.$emit('repeatedOk')
				this.$emit('handleOk')
			},
			resetting() {
				this.imgOptionData = [{
					content: ''
				}, {
					content: ''
				}, {
					content: ''
				}, {
					content: ''
				}]
				this.childExamList = []
				this.form.title = ''
				this.form.labelIds = []
				this.clozeList = []
				this.form.optionsStr = ''
				this.form.answer = ''
				this.form.textExplain = ''
			},
			submitQuestion() {
				this.$refs.form.validate(valid => {
					if (valid) {
						if (this.form.labelIds && this.form.labelIds.length != 0) {
							this.form.labelIds = this.form.labelIds.toString()
						} else {
							this.form.labelIds = ''
						}
						if (this.form.type == 0 || this.form.type == 1 || this.form.type == 12) {
							var optionArr = this.form.optionsStr ? this.form.optionsStr.split('\n') : [];
							this.form.optionList = [];
							let optionIndex = -1
							for (let i = 0; i < optionArr.length; ++i) {
								//去除字符串.之前的ABCD和字符串后面的空格
								if (optionArr[i].indexOf('.') != -1) {
									optionIndex = optionArr[i].indexOf('.')
								} else if (optionArr[i].indexOf('、') != -1) {
									optionIndex = optionArr[i].indexOf('、')
								}
								this.option.content = optionArr[i].substring(optionIndex + 1,
									optionArr[i].length).trim();
								this.option.title = this.optionsArr[i]
								this.form.optionList.push(Object.assign({}, this.option));
							}
						}
						if (this.form.type == 1 || this.form.type == 12) {
							var answer = '';
							for (var i = 0; i < this.form.answerN.length; ++i) {
								answer += this.form.answerN[i] + ',';
							}
							this.form.answer = answer.substring(0, answer.length - 1);
						}
						this.form.function = this.domainArr.toString()
						let param = {
							...this.form
						}
						if (this.form.optionType == 2) {
							for (let index in this.imgOptionData) {
								this.imgOptionData[index].type = 2
								this.imgOptionData[index].title = this.optionsArr[index]
							}
							param = {
								...this.form,
								optionList: this.imgOptionData
							}
						}
						if (this.isMock) {
							this.$emit('handleOk', param)
							return
						}
						// 完形填空
						if (this.form.type == 100) {
							let arr = []
							for (let item of this.clozeList) {
								for (let index in item.content) {
									item.content[index].title = this.optionsArr[index]
								}
								item.content = JSON.stringify(item.content)
							}
							param.questions = this.clozeList
							param.isCloze = true
							this.clozeList = []
						}
						//综合题/阅读理解/文言文/现代文
						if (this.form.type == 99 || this.form.type == 114 || this.form.type == 115 || this.form.type == 113) {
							param.questionChild = this.childExamList
						}
						param.roleType = localStorage.getItem('roleType') == 3 ? 1 : ''
						param.isChild = this.isChild
						this.$post('/admin/question/saveQuestion', param).then(res => {
							if (res.code == 1000) {
								this.$message.success('添加成功')
								this.imgOptionData = [{
									content: ''
								}, {
									content: ''
								}, {
									content: ''
								}, {
									content: ''
								}]
								this.childExamList = []
								this.form.title = ''
								this.form.labelIds = []
								this.clozeList = []
								this.form.optionsStr = ''
								this.form.optionList = []
								this.form.answer = ''
								this.form.answerN = []
								this.form.textExplain = ''
								this.domainArr = []
								this.returnIndex()
							}
						})
					} else {
						return false;
					}
				})
			},
			submitQuestionCheck() {
				if (this.$.isEmpty(this.form.type)) {
					this.$message.warning('请选择题目类型!')
					return
				}
				this.$refs.repeatedQuestions.show()
			},
			handleUploadSuccess(res, file, index) {
				this.imgOptionData[index].content = res.data
			},
			clickPush() {
				this.imgOptionData.push({
					content: ''
				})
			},
			clickSubtract(index) {
				this.imgOptionData.splice(index, 1)
			},
			clickSort(index) {
				if (this.childExamList.length == 1) return;
				if (index == 0) {
					this.childExamList[index].sort = this.childExamList.length - 1
					for (let i = 1; i < this.childExamList.length; i++) {
						this.childExamList[i].sort = index - 1
					}
				} else {
					for (let i = 0; i < this.childExamList.length; i++) {
						if (i == index) {
							this.childExamList[index].sort = index - 1
							this.childExamList[index - 1].sort = index + 1
						}
					}
				}
				this.childExamList.sort((a, b) => {
					return a.sort - b.sort
				})
			},
			clickDel(id) {
				this.childExamList.forEach((item, index) => {
					if (item.id == id) {
						this.childExamList.splice(index, 1)
					}
				})
			},
			//监听单选题，多选题，判断题自动录入
			shibieluru(value) {
				if (!value) return
				var index = -1
				if (value.indexOf('A.') != -1) {
					index = value.indexOf('A.')
				} else if (value.indexOf('A、') != -1) {
					index = value.indexOf('A、')
				}
				if (index != -1) {
					var optionIndex = value.indexOf('答案')
					this.form.title = value.substring(0, index)
					console.log(this.form.title)
					// for (let item of this.indexArr) {
					// 	if (this.form.title.indexOf(item) != -1) {
					// 		var titileIndex = this.form.title.indexOf(item)
					// 		this.form.title = this.form.title.substring(titileIndex + 2, index)
					// 	}
					// }
					if (optionIndex != -1) {
						this.form.optionsStr = value.substring(index - 1, optionIndex).split('\n').filter(item => item).join('\n')
						var answerIndex = value.indexOf('解析')
						if (answerIndex != -1) {
							if (this.form.type == 1) {
								if (value.substring(optionIndex - 1).indexOf('\n') != -1) {
									this.form.answer = value.substring(optionIndex - 1).trim().split('\n')[0].slice(3).split(',')
								} else {
									this.form.answer = value.substring(optionIndex - 1).trim().slice(3).split(',')
								}
								this.form.answerN = this.form.answer
							} else {
								this.form.answer = value.substring(optionIndex - 1, answerIndex).trim().slice(3)
							}
							this.form.textExplain = value.substring(answerIndex - 1).trim().slice(3)
						} else {
							if (this.form.type == 1) {
								this.form.answer = value.substring(optionIndex - 1).trim().slice(3).split(',')
								this.form.answerN = this.form.answer
							} else {
								this.form.answer = value.substring(optionIndex - 1).trim().slice(3)
							}
						}
					} else {
						this.form.optionsStr = value.substring(index - 1).split('\n').filter(item => item).join('\n')
					}
					console.log(this.form.answer, this.form.answerN, "answerN")
				} else if (!this.form.english) {
					this.form.title = value.replace(/[ ]/g, "")
				}

				if (this.isEnter) {
					let questionArr = this.form.title.split('\n');
					let num = 0
					if (this.domainArr.indexOf('英语检测') != -1) {
						num = questionArr.length - 4
					}
					let indexFlag = 0;
					this.form.title = ''
					for (let i = 0; i < questionArr.length; i++) {
						if (questionArr[i] == '') {
							continue;
						} else {
							if (indexFlag == 0 || Number(num) >= i + 1) {
								indexFlag++;
								this.form.title += questionArr[i] + '\n';
							} else {
								if (!questionArr[i].startsWith('答案') && !questionArr[i].startsWith('解析')) {
									this.form.optionsStr += questionArr[i] + '\n';
								} else if (questionArr[i].startsWith('答案')) {
									if (this.form.type === 0 || this.form.type === 1) {
										this.form.answerN = questionArr[i].substr(3, questionArr[i].length).split('');
									} else {
										this.form.answer = questionArr[i].substr(3, questionArr[i].length);
									}
								} else if (questionArr[i].startsWith('解析')) {
									this.form.textExplain = questionArr[i].substr(3, questionArr[i].length);
								}
							}
						}
					}
					if (this.form.optionsStr.endsWith('\n')) {
						this.form.optionsStr = this.form.optionsStr.substr(0, this.form.optionsStr.length - 1);
					}
					this.autoIdentifyStr = '';
					this.isAutoIdentify = false;
				}

			},
			//检测重复加选项
			repeatChange(val) {
				this.isRepeat = val
			},
			// 数学题
			mathChange(val) {
				this.isMath = val
				if (val) {
					this.form.optionType = 2
				} else {
					this.imgOptionData = [{
						content: ''
					}, {
						content: ''
					}, {
						content: ''
					}, {
						content: ''
					}]
				}
			},
			// 英语检测
			englishChange(val) {
				this.form.english = val
			},
			// 快速录入
			clickEntry() {

			},
			async getType() {
				const res = await this.$get('/admin/questionType/getQuestionSort')
				if (res.code != 1000) {
					this.$message.error('搜索服务异常');
					return;
				}
				this.typeList = res.data;
				this.smallTypeList = []
				for (let item of this.typeList) {
					if (item.id == 0 || item.id == 1 || item.id == 2 || item.id == 3 || item.id == 5 || item.id == 6) {
						this.smallTypeList.push(item)
					}
				}
				if (this.isSmall) {
					this.typesData = []
					for (let item of this.typeList) {
						if (item.id == 0 || item.id == 1 || item.id == 2 || item.id == 3 || item.id == 5 || item.id == 6) {
							this.typesData.push(item)
						}
					}
				} else {
					this.typesData = this.typeList.slice(0, 6) || []
				}
			},
			//展开收起
			clickShow() {
				this.isShow = !this.isShow
				let data = this.typeList.slice(0, 6)
				this.typesData = this.isShow ? this.typeList : data
			},
			// 类型变动
			changetype(type) {
				this.childExamList = []
				this.danxuan = false;
				this.duoxuan = false;
				this.panduan = false;
				this.daan = false;
				this.luru = false;
				this.keguan = false;
				this.zhuguan = false;
				if (type == 0) {
					this.keguan = true;
					this.danxuan = true;
					this.luru = true;
				} else if (type == 1 || type == 12) {
					this.keguan = true;
					this.duoxuan = true;
					this.luru = true;
				} else if (type == 2) {
					this.keguan = true;
					this.panduan = true;
				} else {
					this.daan = true;
					this.zhuguan = true;
				}
			},
			//获取题目分类
			async getSort() {
				let isChild = false
				if (this.isChild) {
					isChild = true
				}
				const res1 = await this.$get('/admin/question/getQuestionSort', {
					type: 0
				})
				this.categoryId1s = res1.data.list;
				const res2 = await this.$get('/admin/question/getQuestionSort', {
					type: 1
				})
				this.categoryId2s = res2.data.list;
				const res3 = await this.$get('/admin/question/getQuestionSort', {
					type: 2
				})
				this.categoryId3s = res3.data.list;
				const res4 = await this.$postForm('/admin/question/classList')
				this.classIdData = res4.data.list;
			},
			// 章节分类
			onCategoryChange1(id) {
				this.categoryId1s.find((item) => {
					if (item.id == id) {
						this.form.category1 = item.name
					}
				})
			},
			// 模块分类
			onCategoryChange2(id) {
				this.categoryId2s.find((item) => {
					if (item.id == id) {
						this.form.category2 = item.name
					}
				})
			},
			// 综合分类
			onCategoryChange3(id) {
				this.categoryId3s.find((item) => {
					if (item.id == id) {
						this.form.category3 = item.name
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.category /deep/ .el-form-item__content {
		display: flex;
	}

	/deep/ .is-required {
		display: flex;
		align-items: center;
	}

	/deep/ .el-form-item__label {
		width: 90px !important;
		color: #606266;
		font-weight: 700;
	}

	/deep/ .el-form-item__content {
		margin-left: 0 !important;
	}

	.examText {
		width: 700px;
		border: 1px dashed #ccc;
		margin-top: 10px;
		padding: 0 10px;
		border-radius: 4px;
	}
</style>